var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var jsonConfig = require('./config/config.json');
global.APP_PATH = __dirname;
global.USER_ACCOUNT = '';

var loginController = require('./controllers/login');
var registerController = require('./controllers/register');
var bookController = require('./controllers/nodeBook');
var saveEditController = require('./controllers/saveEdit');
var getUserController = require('./controllers/getUser');
var folderController = require('./controllers/folder');
var previewController = require('./controllers/preview');
var recycleController = require('./controllers/recycle');
var fileController = require('./controllers/file');

//定义数据库
global.conn = mysql.createConnection({
    host: 'localhost',
    user: 'mickey',
    password: 'notebook',
    database:'notebook',
    port: 3306
});

conn.connect(function(error){
    console.log(error)
})

//静态资源使用的路径
app.use(express.static(__dirname + '/public'));


//指定模板引擎
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('views', __dirname + '/view');

app.get('/', function(req, res, next){
    res.render('init');
});

app.get('/book', bookController.initBook);

app.get('/login', loginController.login);

app.get('/register', registerController.register);

app.get('/getFolder', folderController.getFolder);

app.get('/getPreview', previewController.getPreview);

app.get('/getAllPreview', previewController.getAllPreview)

app.get('/saveEdit', saveEditController.saveEdit);

app.get('/saveFolder', folderController.saveFolder);

app.get('/savePreview', previewController.savePreview);

app.get('/deleteFolder', folderController.deleteFolder);

app.get('/deletePreview', previewController.deletePreview);

app.get('/renameFolder', folderController.renameFolder);

app.get('/renamePreview', previewController.renamePreview);

app.get('/getUser', getUserController.getUser);

app.get('/recycle', recycleController.getRecycle);

app.get('/getDeletePreview', recycleController.getDeletePreview);

app.get('/revokeRecycle', recycleController.revokeRecycle);

app.get('/deleteRecycle',recycleController.deleteRecycle);

var multer = require('multer');
var mkdirp = require('mkdirp');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        var dest = './public/uploadFile/' + global.USER_ACCOUNT;
        mkdirp.sync(dest);
        cb(null, dest)
    },
    filename: function (req, file, cb) {
        if(file.originalname != 'blob'){
            cb(null, Date.now() + file.originalname);
        }else{
            cb(null, file.fieldname + '-' + Date.now() + '.' +file.mimetype.split('/')[1]);
        }
    }
});

var upload = multer({
    storage:storage
});

app.use('/uploadFile', upload.single('file'), fileController.uploadFile);



var server = app.listen(3000, function(){
    console.log('Server listening on http://localhost:%d', this.address().port);
});